using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace MoEngine
{
	public class AnimTemplate
	{
		int FrameWidth;
		int FrameHeight;
		int FrameCountX;
		int FrameCountY;
		int m_FrameCount;
		float m_Interval;
		Texture2D Image;

		public AnimTemplate(Texture2D image, int frameCountX, int frameCountY, int emptyFrames, float interval)
		{
			if (image.Width % frameCountX != 0)
				throw new Exception(string.Format("{0} used by AnimTemplate, must have no residual on X: {1} / {2}", image, image.Width, frameCountX));

			if (image.Height % frameCountY != 0)
				throw new Exception(string.Format("{0} used by AnimTemplate, must have no residual on X: {1} / {2}", image, image.Height, frameCountY));

			if (emptyFrames >= frameCountX)
				throw new Exception("emptyFrames must be less than frameCountX");

			Image = image;
			FrameCountX = frameCountX;
			FrameCountY = frameCountY;
			FrameWidth = image.Width / frameCountX;
			FrameHeight = image.Height / frameCountY;
			m_FrameCount = frameCountX * frameCountY - emptyFrames;
			m_Interval = interval;
		}

		public AnimTemplate(Texture2D image, int frameCountX, int frameCountY, int emptyFrames)
			: this(image, frameCountX, frameCountY, emptyFrames, 0.033333f)
		{

		}

		public Rectangle GetRectForFrame(int frame)
		{
			int x = frame % FrameCountX;
			int y = frame / FrameCountX;

			return new Rectangle(x * FrameWidth, y * FrameHeight, FrameWidth, FrameHeight);
		}

		public int FrameCount
		{
			get { return m_FrameCount; }
		}

		public int Width
		{
			get { return FrameWidth; }
		}

		public int Height
		{
			get { return FrameHeight; }
		}

		public float Interval
		{
			get { return m_Interval; }
		}

		public void Render(SpriteBatch spriteBatch, Rectangle rect, int frame)
		{
			spriteBatch.Draw(Image, rect, GetRectForFrame(frame), Color.White);
		}
	}
}
